﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using VAdvantage.Controls;
using VAdvantage.Model;
using VAdvantage.Classes;
using VAdvantage.Apps;
using VAdvantage.ProcessEngine;
using VAdvantage.Utility;
using VAdvantage.Grids;
using System.Windows.Controls;
using System.Collections;
using System.Windows;
using System.Threading;

namespace VAdvantage.Framework
{
    public partial class CrystalParameter : ChildWindow
    {
        public Context ctx = Utility.Envs.GetContext();
        private int windowNo = 0;
        List<GridField> lstFields = new List<GridField>(30);
        List<IControl> lstVEditors = new List<IControl>();

        List<GridField> lstFields2 = new List<GridField>(30);
        List<IControl> lstVEditors2 = new List<IControl>();

        private bool _isOK = false;
        FormFrame _frame = null;
        List<String> _colName = null;
        MForm mForm = null;
        public CrystalParameter(int _windowNo, VAdvantage.Apps.FormFrame frame)
        {
            windowNo = _windowNo;
            _frame = frame;
            InitializeComponent();
        }

        public CrystalParameter(int _windowNo)
            
        {
            windowNo = _windowNo;
            InitializeComponent();
        }

        public bool InitDialog(int AD_Form_ID, bool fill, out List<String> colName)
        {
            mForm = new VAdvantage.Model.MForm(Envs.GetCtx(), AD_Form_ID, null);
            string strSql = "";
            SqlParameter[] param;
            List<String> tempColName = new List<string>();

            param = new SqlParameter[1];
            param[0] = new SqlParameter("@formid", AD_Form_ID);
            strSql = "SELECT p.Name, p.Description, "
                + "p.AD_Reference_ID, p.AD_CrystalReport_Para_ID, "
                + "p.FieldLength, p.IsMandatory IsMandatoryUI, p.IsRange, p.ColumnName, "
                + "p.DefaultValue, p.SeqNo, p.AD_Reference_Value_ID, vr.Code AS ValidationCode "
                + "FROM AD_CrystalReport_Para p"
                + " LEFT OUTER JOIN AD_Val_Rule vr ON (p.AD_Val_Rule_ID=vr.AD_Val_Rule_ID) "
                + "WHERE p.AD_Form_ID=@formid"		//	1
                + " AND p.IsActive='Y' "
                + "ORDER BY SeqNo";


            DataSet ds = DataBase.DB.ExecuteDataset(strSql, param, null);

            if (fill)
            {
                for (int cols = 0; cols <= ds.Tables[0].Rows.Count - 1; cols++)
                {
                    tempColName.Add(ds.Tables[0].Rows[cols]["ColumnName"].ToString());
                }


            }
            colName = tempColName;
            if (ds.Tables[0].Rows.Count > 0)
            {
                hasFields = true;
                dsFields = ds;
            }
            //else
            //    return false;



            //formHeight = (ds.Tables[0].Rows.Count + 70);
            return hasFields;
        }

        public bool InitDialog(int AD_Form_ID)
        {
            return InitDialog(AD_Form_ID, false, out _colName);
        }

        /// <summary>
        /// Initializes the dialog box
        /// </summary>
        /// <returns>true or false</returns>
        public bool InitDialog()
        {
            return InitDialog(_frame.Get_Ad_Form_ID());
        }

        ArrayList ctrlList = new ArrayList();
        private int m_sLine = 0;
        private int fixedWidth = 0;
        VComboBox cmbSelected = null;

        private void CreateField(DataRow dr)
        {
            GridFieldVO fvo = GridFieldVO.CreateCrystalParameter(Utility.Envs.GetContext(), windowNo, dr);
            GridField fo = new GridField(fvo);
            lstFields.Add(fo);
            Object defaultObject = fo.GetDefault();
            bool created = false;

            Deployment.Current.Dispatcher.BeginInvoke
            (delegate
            {

                IControl ctrl = null;
                ctrl = VControlFactory.GetControl(null, fo, false, false, false);


                fo.SetValue(defaultObject, true);

                VLabel label = VControlFactory.GetLabel(fo);


                if (ctrl is VComboBox)
                {
                    cmbSelected = (VComboBox)ctrl;
                    cmbSelected.SelectionChanged += new SelectionChangedEventHandler(cmbSelected_SelectionChanged);
                    //ctrl.VetoableChangeListener += new System.EventHandler(this.hello);
                }

                RowDefinition row = new RowDefinition();
                row.Height = new GridLength(0, GridUnitType.Auto);
                row.MinHeight = 30;
                tblpnlS.RowDefinitions.Add(row);


                if (m_sLine == 0)
                {
                    ColumnDefinition column = new ColumnDefinition();
                    column.Width = new GridLength(30, GridUnitType.Star);
                    tblpnlS.ColumnDefinitions.Add(column);

                    column = new ColumnDefinition();
                    column.Width = new GridLength(70, GridUnitType.Star);
                    tblpnlS.ColumnDefinitions.Add(column);

                }

                if (label != null)
                {
                    label.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
                    label.VerticalAlignment = System.Windows.VerticalAlignment.Top;
                    label.Margin = new Thickness(0, 0, 5, 0);

                    Grid.SetColumn(label, 0);
                    Grid.SetRow(label, m_sLine);
                    tblpnlS.Children.Add(label);
                }
                if (ctrl != null)
                {

                    Control c = (Control)ctrl;
                    Grid.SetColumn(c, 1);
                    Grid.SetRow(c, m_sLine);
                    tblpnlS.Children.Add(c);
                    c.VerticalAlignment = System.Windows.VerticalAlignment.Top;
                    c.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
                    c.Margin = new Thickness(0, 0, 5, 0);
                    c.Height = 23;
                    c.Width = 270;
                    lstVEditors.Add(ctrl);
                    ctrl.SetValue(defaultObject);
                }


                if (fvo.isRange)
                {
                    row = new RowDefinition();
                    row.Height = new GridLength(0, GridUnitType.Auto);
                    row.MinHeight = 30;
                    tblpnlS.RowDefinitions.Add(row);

                    GridFieldVO fvo2 = GridFieldVO.CreateParameter(fvo);
                    GridField fo2 = new GridField(fvo2);
                    lstFields2.Add(fo2);

                    IControl ctrl2 = null;
                    ctrl2 = VControlFactory.GetControl(null, fo2, false, false, false);

                    Object defaultObject2 = fo2.GetDefault();
                    fo2.SetValue(defaultObject2, true);

                    m_sLine++;

                    Control c2 = (Control)ctrl2;
                    Grid.SetRow(c2, m_sLine);
                    Grid.SetColumn(c2, 1);

                    c2.VerticalAlignment = System.Windows.VerticalAlignment.Top;
                    c2.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
                    c2.Margin = new Thickness(0, 0, 5, 0);
                    c2.Height = 23;
                    c2.Width = 270;

                    tblpnlS.Children.Add(c2);
                    lstVEditors2.Add(ctrl2);

                    ctrl2.SetValue(defaultObject2);
                }
                else
                {
                    lstVEditors2.Add(null);
                    lstFields2.Add(null);
                }

                m_sLine++;
                //tblpnlS.Height = (50 * m_sLine);

                created = true;

            });


            while (!created)
            {
                Thread.Sleep(5);
            }

            created = false;
        }

        void cmbSelected_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //	log.fine( "ProcessParameter.vetoableChange");
            String value = ((IControl)sender).GetValue().ToString();// evt.getNewValue() == null ? "" : evt.getNewValue().toString();
            Utility.Envs.GetCtx().SetContext(windowNo, ((Control)sender).Name, value);
        }


        /// <summary>
        /// Check the status of OK button
        /// </summary>
        /// <returns></returns>
        public bool IsOK()
        {
            return _isOK;
        }


        bool _includeProc = false;
        /// <summary>
        /// Check the status of OK button
        /// </summary>
        /// <returns></returns>
        public void IncludeProc(bool val)
        {
            _includeProc = val;
        }



        bool hasFields = false;
        private DataSet dsFields = null;
        private Double formHeight = 0;

        private void CrystalParameter_Load(object sender, EventArgs e)
        {
            this.Visibility = System.Windows.Visibility.Collapsed;
            SetBusy(true);
            ThreadPool.QueueUserWorkItem(delegate
            {
                int ss = 1;
                foreach (DataRow dr in dsFields.Tables[0].Rows)
                {
                    CreateField(dr);
                    ss++;
                }

                Dispatcher.BeginInvoke(delegate
                {
                    SetBusy(false);
                    this.Visibility = System.Windows.Visibility.Visible;
                });
            });
            //this.Width = tblpnlS.Width + 30;
           // this.Height = tblpnlS.Height + 100;
        }

        private void SetBusy(bool isbusy)
        {
            busyWindow.IsBusy = isbusy;
            btnOK.IsEnabled = !isbusy;
        }

        /// <summary>
        /// Fetches the values entered into textbox and updates into DB
        /// </summary>
        //protected bool SaveParameter()
        //{

        //    //check mandatory status and give appropriate message
        //    StringBuilder sb = new StringBuilder("");
        //    int iSize = lstFields.Count();
        //    for (int i = 0; i <= iSize - 1; i++)
        //    {
        //        GridField fo = (GridField)lstFields[i];
        //        if (fo.IsMandatory(true))   //check if mandatory
        //        {
        //            //fetch data from fields
        //            IControl vco = lstVEditors[i];
        //            Object objData = vco.GetValue();
        //            if (objData == null || objData.ToString().Length == 0)
        //            {
        //                if (sb.ToString().Length > 0)
        //                    sb.Append(", ");
        //                sb.Append(fo.GetHeader());
        //            }
        //            else
        //                fo.SetError(false);


        //            IControl editor2 = null;
        //            if (lstVEditors2.Count > 0)
        //                editor2 = lstVEditors2[i];

        //            if (editor2 != null)
        //            {
        //                Object data2 = vco.GetValue();
        //                GridField fo2 = (GridField)lstFields2[i];
        //                if (data2 == null || data2.ToString().Length == 0)
        //                {
        //                    fo2.SetError(true);
        //                    if (sb.Length > 0)
        //                        sb.Append(", ");
        //                    sb.Append(fo.GetHeader());
        //                }
        //                else
        //                    fo2.SetError(false);
        //            }   //range field
        //        }   //mandatory
        //    }//field loop


        //    if (sb.ToString().Length != 0)  //if length is 0, then  show message
        //    {
        //        ShowMessage.Error("FillMandatory", true, sb.ToString());
        //        //MessageBox.Show("Fill mandatory fileds");
        //        return false;
        //    }

        //    //save now *******************************************
        //    BackgroundWorker bgw = new BackgroundWorker();
        //    bgw.DoWork += (ov, ev) =>
        //        {
        //    for (int i = 0; i < lstFields.Count(); i++)
        //    {
        //        Object objResult = null;
        //        Object objResult2 = null;
        //        if (!mForm.IsIncludeProcedure())
        //        {
        //            //Don't save null values
        //            if (objResult == null && objResult2 == null)
        //                continue;

        //            if (objResult == DBNull.Value)
        //                continue;
        //        }

        //        //create parameter
        //        MCrystalInstancePara para = new MCrystalInstancePara(ctx, GetAD_CrystalInstance_ID(), i);
        //        GridField fo = (GridField)lstFields[i];
        //        para.SetParameterName(fo.GetColumnName());

        //         IControl editor = lstVEditors[i];

        //                IControl editor2 = null;
        //                if (lstVEditors2.Count > 0)
        //                    editor2 = lstVEditors2[i];
                        

        //                bool doMove = false;
        //                Dispatcher.BeginInvoke(delegate
        //                {
        //               objResult = editor.GetValue();

        //                    if (editor2 != null)
        //                    {

        //                        objResult2 = editor2.GetValue();

        //                    }

        //                    doMove = true;
        //                });
        //         while (!doMove)
        //                    Thread.Sleep(1);

        //                doMove = false;

                
        //                //Don't save null values
        //                if (objResult == null && objResult2 == null)
        //                    continue;

        //        bool b = System.Windows.Deployment.Current.Dispatcher.CheckAccess();

        //        //date
        //        if (objResult is DateTime || objResult2 is DateTime)
        //        //if (objResult.GetType() == typeof(DateTime) && objResult2.GetType() == typeof(DateTime))
        //        {
        //            para.SetP_Date((DateTime?)objResult);
        //            if (objResult2 == DBNull.Value)
        //            {
        //                objResult2 = null;
        //            }
        //            if (editor2 != null && objResult2 != null)
        //            {

        //                para.SetP_Date_To((DateTime)objResult2);
        //            }

        //        }
        //        else if (objResult.GetType() == typeof(int))
        //        {
        //            if (objResult != null)
        //            {
        //                int ii = (int)objResult;
        //                para.SetP_Number(ii);
        //            }
        //            if (editor2 != null && objResult2 != null)
        //            {
        //                int ii = (int)objResult2;
        //                para.SetP_Number_To(ii);
        //            }
        //        }
        //        else if (objResult.GetType() == typeof(decimal))
        //        {
        //            para.SetP_Number((decimal)objResult);
        //            if (editor2 != null && objResult2 != null)
        //                para.SetP_Number_To((decimal)objResult2);
        //        }
        //        else if (objResult.GetType() == typeof(bool))
        //        {
        //            bool bln = (bool)objResult;
        //            String value = bln ? "Y" : "N";
        //            para.SetP_String(value);

        //        }
        //        else
        //        {
        //            if (objResult != null)
        //                para.SetP_String(objResult.ToString());
        //            if (editor2 != null && objResult2 != null)
        //                para.SetP_String_To(objResult2.ToString());
        //        }

        //        Dispatcher.BeginInvoke(delegate
        //                {
        //                    para.SetInfo(editor.GetText());
        //                    if (editor2 != null)
        //                        para.SetInfo_To(editor2.GetText());

        //                    doMove = true;
        //                });

        //                while (!doMove)
        //                    Thread.Sleep(1);

        //                doMove = false;

        //        bool b1 = para.Save();
        //    }
        //            _isOK = true;
        //             Dispatcher.BeginInvoke(delegate
        //            {
        //                this.DialogResult = true;
        //            });

        //            //process = new ProcessCtl(_parent, pi, null);
        //            //process.Run();

        //        };
        //    //return true;
        //     bgw.RunWorkerAsync();
        //}

     
        public int GetAD_CrystalInstance_ID()
        {
            return AD_CrystalInstance_ID;
        }

        private int AD_CrystalInstance_ID = 0;
        public void SetAD_CrystalInstance_ID(int id)
        {
            AD_CrystalInstance_ID = id;
        }

        private void OKButton_Click(object sender, EventArgs e)
        {
            _isOK = false;
            //check mandatory status and give appropriate message
            SetBusy(true);

            StringBuilder sb = new StringBuilder("");
            int iSize = lstFields.Count();
            for (int i = 0; i <= iSize - 1; i++)
            {
                GridField fo = (GridField)lstFields[i];
                if (fo.IsMandatory(true))   //check if mandatory
                {
                    //fetch data from fields
                    IControl vco = lstVEditors[i];
                    Object objData = vco.GetValue();
                    if (objData == null || objData.ToString().Length == 0)
                    {
                        if (sb.ToString().Length > 0)
                            sb.Append(", ");
                        sb.Append(fo.GetHeader());
                    }
                    else
                        fo.SetError(false);


                    IControl editor2 = null;
                    if (lstVEditors2.Count > 0)
                        editor2 = lstVEditors2[i];

                    if (editor2 != null)
                    {
                        Object data2 = vco.GetValue();
                        GridField fo2 = (GridField)lstFields2[i];
                        if (data2 == null || data2.ToString().Length == 0)
                        {
                            fo2.SetError(true);
                            if (sb.Length > 0)
                                sb.Append(", ");
                            sb.Append(fo.GetHeader());
                        }
                        else
                            fo2.SetError(false);
                    }   //range field
                }   //mandatory
            }//field loop


            if (sb.ToString().Length != 0)  //if length is 0, then  show message
            {
                ShowMessage.Error(Msg.GetMsg("FillMandatory"), true, sb.ToString());
                SetBusy(false);
                return;
                //MessageBox.Show("Fill mandatory fileds");
                //return false;
            }

            SetBusy(true);
            BackgroundWorker bgw = new BackgroundWorker();
            bgw.DoWork += (ov, ev) =>
            {
                for (int i = 0; i < lstFields.Count(); i++)
                {

                    MCrystalInstancePara para = null;
                    GridField fo = null;

                    para = new MCrystalInstancePara(ctx, GetAD_CrystalInstance_ID(), i);
                    fo = (GridField)lstFields[i];

                    IControl editor = lstVEditors[i];

                    IControl editor2 = null;
                    if (lstVEditors2.Count > 0)
                        editor2 = lstVEditors2[i];
                    Object objResult = null;
                    Object objResult2 = null;

                    bool doMove = false;
                    Dispatcher.BeginInvoke(delegate
                    {
                        objResult = editor.GetValue();

                        if (editor2 != null)
                        {

                            objResult2 = editor2.GetValue();

                        }

                        doMove = true;
                    });

                    while (!doMove)
                        Thread.Sleep(10);

                    doMove = false;

                        if (!mForm.IsIncludeProcedure())
                        {
                            //Don't save null values
                            if (objResult == null && objResult2 == null)
                                continue;

                            if (objResult == DBNull.Value)
                                continue;
                        }

                        //create parameter
                       
                        para.SetParameterName(fo.GetColumnName());

                        //date
                        if (objResult is DateTime || objResult2 is DateTime)
                        //if (objResult.GetType() == typeof(DateTime) && objResult2.GetType() == typeof(DateTime))
                        {
                            para.SetP_Date((DateTime?)objResult);
                            if (objResult2 == DBNull.Value)
                            {
                                objResult2 = null;
                            }
                            if (editor2 != null && objResult2 != null)
                            {

                                para.SetP_Date_To((DateTime)objResult2);
                            }

                        }
                        else if (objResult is int)
                        {
                            if (objResult != null)
                            {
                                int ii = (int)objResult;
                                para.SetP_Number(ii);
                            }
                            if (editor2 != null && objResult2 != null)
                            {
                                int ii = (int)objResult2;
                                para.SetP_Number_To(ii);
                            }
                        }
                        else if (objResult is decimal)
                        {
                            para.SetP_Number((decimal)objResult);
                            if (editor2 != null && objResult2 != null)
                                para.SetP_Number_To((decimal)objResult2);
                        }
                        else if (objResult  is bool)
                        {
                            bool bln = (bool)objResult;
                            String value = bln ? "Y" : "N";
                            para.SetP_String(value);

                        }
                        else
                        {
                            if (objResult != null)
                                para.SetP_String(objResult.ToString());
                            if (editor2 != null && objResult2 != null)
                                para.SetP_String_To(objResult2.ToString());
                        }
                        Dispatcher.BeginInvoke(delegate
                        {
                            para.SetInfo(editor.GetText());
                            if (editor2 != null)
                                para.SetInfo_To(editor2.GetText());

                            doMove = true;
                        });

                        while (!doMove)
                            Thread.Sleep(10);

                        doMove = false;



                        bool save = para.Save();
                        if (save)
                        {
                            //saveParameter = true;


                        }
                }

                _isOK = true;

                Dispatcher.BeginInvoke(delegate
                {
                    SetBusy(false);
                    this.DialogResult = true;
                });

                //process = new ProcessCtl(_parent, pi, null);
                //process.Run();

            };

            bgw.RunWorkerAsync();
        }

        private void CancelButton_Click(object sender, EventArgs e)
        {
            Utility.Envs.SetBusyIndicator(false);
            this.DialogResult = false;
        }
       
    }
}
